<template>
  <div class="app-container customer-div">
<!--    <div style="font-size:14px;color:#606266">SAP更新日期：{{JDupdate}}</div>-->
    <el-menu :default-active="listQuery.sendType" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="all">全部</el-menu-item>
      <el-menu-item index="unFinish">未发货</el-menu-item>
      <el-menu-item index="finished">已完成</el-menu-item>
      <el-menu-item index="outTime">超过预计发货时间</el-menu-item>
      <el-menu-item index="unPlan">待排货</el-menu-item>
      <el-menu-item index="yap">已排货</el-menu-item>
      <el-menu-item index="saleContractDetailStatistics" v-if="saleContractDetailStatistics">合同统计</el-menu-item><!--v-if="saleContractStatistics"-->
    </el-menu>
    <div v-if="listQuery.sendType !='yap' && listQuery.sendType !='saleContractDetailStatistics'">
      <div style="margin-top: 20px">
        <!--搜索-->
        <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
          <div class="search-div">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="常用搜索条件" name="1">
                <el-form-item label="订单编号：">
                  <el-input v-model="listQuery.orderSn"></el-input>
                </el-form-item>
                <el-form-item label="客户名称：">
                  <el-autocomplete
                    clearable
                    class="inline-input"
                    value-key="customerName"
                    :fetch-suggestions="querySearch"
                    v-model="listQuery.customerName"
                    placeholder="请输入内容"
                    @select="handleSelectCustomerName"
                    :trigger-on-focus="false"
                  ></el-autocomplete>
                </el-form-item>
                <el-form-item label="品名：" >
                  <el-input v-model="listQuery.goodsName" style="width:150px"></el-input>
                </el-form-item>
                <el-form-item label="牌号：">
                  <el-autocomplete
                    clearable
                    style="width:300px;"
                    class="inline-input"
                    v-model="listQuery.goodsSn"
                    :fetch-suggestions="querySearchGoodsSn"
                    placeholder="请输入内容"
                    @select="handleSelectGoodsSn"
                  >
                    <template slot-scope="{ item }">
                      <div>{{ item.goodsSn }}</div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
                <el-form-item label="业务员：">
                  <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable style="width:150px">
                    <el-option
                      v-for="item in userOptionList"
                      :key="item.userId"
                      :label="item.userName"
                      :value="item.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="事业部：" >
                  <el-select v-model="listQuery.divsionDeptId" placeholder="请选择" clearable>
                    <el-option :value="item.divsionDeptId" :label="item.divsionDeptName" :key="item.divsionDeptId" v-for="item in divisionList"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="合同流转状态：">
                  <el-select v-model="listQuery.orderState" class="input-width" style="width:195px" placeholder="请选择" clearable>
                    <el-option :value="item.orderState" :label="item.text" :key="item.orderState" v-for="item in orderStateList"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="订单分类：">
                  <el-select v-model="listQuery.orderCustomerType" multiple placeholder="请选择" clearable>
                    <el-option
                      v-for="(item,index) in orderCustomerTypeList"
                      :key="index"
                      :label="item.cddValue"
                      :value="item.cddValue">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否新客户：">
                  <el-select v-model="listQuery.isNewCustomerOrder" placeholder="请选择" clearable style="width:100px">
                    <el-option :key="1" label="是" :value="1"></el-option>
                    <el-option :key="0" label="否" :value="0"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="订单日期：">
                  <el-date-picker
                    v-model="listQuery.createDate"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
              </el-collapse-item>
              <el-collapse-item title="高级搜索条件" name="2">
                <el-form-item label="客户编号：">
                  <el-input v-model="listQuery.customerNumber" style="width:150px"></el-input>
                </el-form-item>

                <el-form-item label="财务状态：">
                  <el-select v-model="listQuery.financeState" placeholder="请选择" clearable multiple style="width:150px">
                    <el-option key="0" label="未审核" value="0"></el-option>
                    <el-option key="1" label="已审核" value="1"></el-option>
                    <el-option key="2" label="已关闭" value="2"></el-option>
                    <el-option key="3" label="部分审核" value="3"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="客户标签：" >
                  <el-select v-model="listQuery.tagIds" clearable multiple>
                    <el-option
                      v-for="item in tagIdList"
                      :key="item.tagId"
                      :label="item.tagName"
                      :value="item.tagId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="客户购买原因：" >
                  <el-select v-model="listQuery.customerBuyReason" size="small" clearable multiple>
                    <el-option :value="item.cddId" :label="item.cddValue" :key="item.cddId" v-for="item in customerBuyReasonList"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="从我司购买原因：" >
                  <el-select v-model="listQuery.fromBuyReason" size="small" clearable multiple>
                    <el-option :value="item.cddId" :label="item.cddValue" :key="item.cddId" v-for="item in fromBuyReasonList"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否后结算订单：">
                  <el-select v-model="listQuery.isDelaySettleOrder" placeholder="请选择" clearable style="width:100px;">
                    <el-option :key="1" label="是" :value="1"></el-option>
                    <el-option :key="0" label="否" :value="0"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否为外贸订单：">
                  <el-select v-model="listQuery.isChina" placeholder="请选择" clearable style="width:100px">
                    <el-option :key="2" label="是" :value="2"></el-option>
                    <el-option :key="1" label="否" :value="1"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="期望发货日期：">
                  <el-date-picker
                    :default-time="['00:00:00', '23:59:59']"
                    v-model="listQuery.expectSendDate"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="预计发货时间：">
                  <el-date-picker
                    :default-time="['00:00:00', '23:59:59']"
                    v-model="listQuery.sendDate"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="取消时间：">
                  <el-date-picker
                    :default-time="['00:00:00', '23:59:59']"
                    v-model="listQuery.financeCancelDate"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
              </el-collapse-item>
            </el-collapse>
            <div style="text-align: right;padding-top:12px;">
              <el-button
                size="small"
                @click="handleSearchList()"
                type="primary">
                查询
              </el-button>
              <el-button
                size="small"
                v-if="saleContractDetailsExport"
                :loading="btnLoading2"
                @click="downloadExcel()">
                导出
              </el-button>
            </div>
          </div>


        </el-form>
      </div>
      <!--数据列表-->
      <div class="table-container">
        <div style="font-size:14px;line-height: 30px;padding:10px 0 ">
          合同数量：<span style="font-weight: bold">{{goodsNum}}</span>
          <span style="padding-left:20px;">未发货数量：</span><span style="font-weight: bold">{{unSendNum}}</span>
          <span style="padding-left:20px;">实际未发货数量：</span><span style="font-weight: bold">{{actualUnSendNum}}</span>
          <span style="padding-left:20px;">合同预估销售毛利：</span><span style="font-weight: bold">{{allPredictProfit}}元</span>
          <span style="padding-left:20px;">合同预估总销售毛利（财务已审核）：</span><span style="font-weight: bold">{{predictProfit}}元</span>
        </div>
        <el-table
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column  label="订单日期" width="100" align="center" prop="createTime">
          </el-table-column>
          <el-table-column  label="订单号" width="150" align="center">
            <template slot-scope="scope">
              <el-link @click="toDetail('edit',scope.row)" type="primary" style="font-size:12px;vertical-align: middle">
                {{scope.row.orderSn}}
              </el-link>
              <img src="../../assets/images/yue.png" v-if="scope.row.isTimeSure == 1" style="vertical-align: middle;"/>
              <img src="../../assets/images/xianshang.png" v-if="scope.row.isMoresuOnlineOrder == 1"  style="vertical-align: middle;"/>
            </template>
          </el-table-column>

          <el-table-column
            label="客户编号"
            width="300">
            <template slot-scope="scope">
              <el-link @click="toCustomerDetail(scope.row)" type="primary" style="font-size:12px">
                {{scope.row.customerNumber}}
              </el-link>
              <!--是否有权限-->
              <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            label="客户标签"
            width="150">
            <template slot-scope="scope">
              <el-tooltip placement="bottom" effect="light">
                <div slot="content" style="max-width: 400px"> <crm-tag :item="item" v-for="item in scope.row.customerTag" :key="item.tagName" style="margin-bottom:4px;margin-right:4px"></crm-tag></div>
                <div style="padding:0 10px;width:100%; white-space: nowrap;  overflow: hidden; text-overflow: ellipsis;">
                  <crm-tag :item="item" v-for="item in scope.row.customerTag" :key="item.tagName" style="margin-bottom:4px;margin-right:4px"></crm-tag>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            label="业务员"
            align="center"
            width="80">
            <template slot-scope="scope">
              {{scope.row.userRealName}}
            </template>
          </el-table-column>
          <el-table-column
            prop="goodsName"
            label="商品名称"
            width="300">
          </el-table-column>
          <el-table-column
            prop="goodsNum"
            label="合同数量"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="sendNum"
            label="已发货数量"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="unSendNum"
            label="未发货数量"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            prop="actualUnSendNum"
            label="实际未发货数量"
            width="150"
            align="center">
          </el-table-column>
          <el-table-column
            prop="unPlanNum"
            label="未排货数量"
            width="150"
            align="center">
          </el-table-column>
          <el-table-column
            prop="goodsPrice"
            label="合同单价"
            width="100"
            align="center">
          </el-table-column>
          <el-table-column
            label="杂费(装卸费)"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.consultation}}
            </template>
          </el-table-column>
          <el-table-column
            label="合计金额"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.goodsAmount}}
            </template>
          </el-table-column>
          <el-table-column
            label="期望发货日期"
            width="120"
            align="center">
            <template slot-scope="scope">
              <span style="vertical-align: middle">{{scope.row.expectSendDate}}</span><img v-if="scope.row.urgentTypeIcon != ''" :src="scope.row.urgentTypeIcon" style="width:14px;vertical-align: middle;margin-left:5px"/>
            </template>
          </el-table-column>
          <el-table-column
            label="发货紧急度"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.urgentTypeStr}}
            </template>
          </el-table-column>
          <el-table-column
            label="合同约定时间"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.timeSureDate}}
            </template>
          </el-table-column>
          <el-table-column
            label="预计发货日期"
            width="120"
            align="center">
            <template slot-scope="scope">
              {{scope.row.sendDate}}
            </template>
          </el-table-column>
          <el-table-column
            label-class-name="bgth"
            label="合同摩叔运费"
            width="80"
            align="center">
            <template slot-scope="scope">
              {{scope.row.freight}}
            </template>
          </el-table-column>
          <el-table-column
            label-class-name="bgth"
            label="采购预估底价"
            width="80"
            align="center">
            <template slot-scope="scope">
              {{scope.row.purchasePrice}}
            </template>
          </el-table-column>

          <el-table-column
            label="预估毛利"
            width="100"
            align="center">
            <template slot-scope="scope">
              <span style="color:red">{{scope.row.saleProfit}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="财务状态"
            width="80">
            <template slot-scope="scope">
              {{scope.row.financeState}}
            </template>
          </el-table-column>
          <el-table-column
            label="行备注"
            width="200">
            <template slot-scope="scope">
              {{scope.row.remark}}
            </template>
          </el-table-column>
          <el-table-column
            label="结算方式"
            width="200">
            <template slot-scope="scope">
              {{scope.row.orderRemark}}
            </template>
          </el-table-column>
          <el-table-column
            label="价格类型"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.priceType}}
            </template>
          </el-table-column>
          <el-table-column
            label="预计发货仓库"
            width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.warehouseName}}
            </template>
          </el-table-column>

          <el-table-column
            label="运费承担"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.freightType | fifFreightType }}
            </template>
          </el-table-column>

          <el-table-column
            label="合同流转状态"
            width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.orderStateStr}}
            </template>
          </el-table-column>
          <el-table-column
            label="财务审核时间"
            width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.financeConfirmTime }}
            </template>
          </el-table-column>
          <el-table-column
             label="订单种类"
             width="100"
             align="center">
             <template slot-scope="scope">
               {{scope.row.isChina}}
             </template>
           </el-table-column>
          <el-table-column
            fixed="right"
            label="从我司购买原因"
            width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.customerBuyReason}}
            </template>
          </el-table-column>
          <el-table-column
            label="客户购买原因"
            fixed="right"
            width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.fromBuyReason}}
            </template>
          </el-table-column>
          <el-table-column
            label="取消时间"
            width="130"
            align="center">
            <template slot-scope="scope">
              {{scope.row.financeCancelTime}}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[10,15,20]"
          :total="count">
        </el-pagination>
      </div>
    </div>

    <div v-else-if="listQuery.sendType =='yap'">
        <dischargingGoods ref="dischargingGoods"></dischargingGoods>
    </div>

    <div v-else-if="listQuery.sendType =='saleContractDetailStatistics'">
      <div style="margin-top:20px">
        <el-radio-group v-model="listQuery2.tab" @change="handleSelect2" size="small">
          <el-radio-button label="my">我的</el-radio-button>
          <el-radio-button label="depart" v-if="departSaleContractDetailStatistics">军团</el-radio-button>
          <el-radio-button label="all" v-if="allSaleContractDetailStatistics">全部</el-radio-button>
        </el-radio-group>
      </div>

      <div style="margin-top: 20px">
        <!--搜索-->
        <el-form :inline="true" :model="listQuery2" size="mini" label-width="120px">
          <el-form-item label="订单编号：">
            <el-input v-model="listQuery2.orderSn"></el-input>
          </el-form-item>
          <el-form-item label="订单日期：">
            <el-date-picker
              v-model="listQuery2.createDate"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="商品分类：" >
            <el-input v-model="listQuery2.goodsName"></el-input>
          </el-form-item>
          <el-form-item label="牌号：">
            <el-autocomplete
              clearable
              style="width:300px;"
              class="inline-input"
              v-model="listQuery2.goodsSn"
              :fetch-suggestions="querySearchGoodsSn"
              placeholder="请输入内容"
              @select="handleSelectGoodsSn"
            >
              <template slot-scope="{ item }">
                <div>{{ item.goodsSn }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="发货单号：" >
            <el-input v-model="listQuery2.deliverSn"></el-input>
          </el-form-item>
          <el-form-item label="发货状态：" >
            <el-select v-model="listQuery2.deliverState" placeholder="请选择" multiple >
              <el-option key="提前" label="提前" value="提前"></el-option>
              <el-option key="延迟" label="延迟" value="延迟"></el-option>
              <el-option key="正常" label="正常" value="正常"></el-option>
              <el-option key="待财务审核" label="待财务审核" value="待财务审核"></el-option>
              <el-option key="未到发货时间" label="未到发货时间" value="未到发货时间"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="提前发货：" >
            <el-input  v-model="day1" type="number" style="width:50px;"></el-input>
            <span style="padding:0 5px">到</span>
            <el-input v-model="day2" type="number" style="width:50px;"></el-input>
            <span style="padding-left:5px">天</span>
          </el-form-item>
          <el-form-item label="发货类型：" >
            <el-select v-model="listQuery2.sendType" placeholder="请选择" multiple >
              <el-option key="公司发货" label="公司发货" value="公司发货"></el-option>
              <el-option key="采购发货" label="采购发货" value="采购发货"></el-option>
              <el-option key="客户自提" label="客户自提" value="客户自提"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="付款时效：" >
            <el-select v-model="listQuery2.payTimeState" placeholder="请选择" multiple >
              <el-option key="尚未付款" label="尚未付款" value="尚未付款"></el-option>
              <el-option key="货到付款" label="货到付款" value="货到付款"></el-option>
              <el-option key="按时付款" label="按时付款" value="按时付款"></el-option>
              <el-option key="延后付款" label="延后付款" value="延后付款"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              @click="handleSearchList2()"
              type="primary">
              查询
            </el-button>
            <el-button
              v-if="saleContractDetailsExport"
              :loading="btnLoading3"
              @click="downloadExcel2()">
              导出
            </el-button>
          </el-form-item>

        </el-form>
      </div>
      <!--数据列表-->
      <div class="table-container">
        <el-table
          v-loading="listLoading2"
          :data="tableData2"
          border
          style="width: 100%; margin-top: 20px">

          <el-table-column  label="订单号" width="150" align="center" key="101">
            <template slot-scope="scope">
              <el-link @click="toDetail('edit',scope.row)" type="primary" style="font-size:12px;">
                {{scope.row.orderSn}}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column  label="订单日期" width="100" align="center" prop="createDate">
          </el-table-column>

          <el-table-column  label="付款时效" width="100" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.payTimeState < 0 " style="color:Red">{{scope.row.payTimeState}}</span>
              <span v-else>{{scope.row.payTimeState}}</span>
            </template>
          </el-table-column>

          <el-table-column  label="订单审核日期" width="100" align="center" prop="financeTime">
          </el-table-column>

          <el-table-column  label="预计付款时间" width="150" align="center" prop="expectPayTime">
          </el-table-column>

          <el-table-column
            prop="goodsName"
            label="商品名称"
            width="300">
          </el-table-column>

          <el-table-column
            prop="goodsNum"
            label="合同数量"
            width="100"
            align="center">
          </el-table-column>

          <el-table-column
            label="期望发货日期"
            width="120"
            align="center" prop="expectSendDate">
          </el-table-column>
          <el-table-column
            label="发货紧急度"
            width="100"
            align="center" prop="urgentType">
          </el-table-column>

          <el-table-column
            label="采购首次确认人"
            width="120"
            align="center" prop="purchaseUserName">
          </el-table-column>

          <el-table-column
            key="11"
            label="预计发货日期"
            width="120"
            align="center">
            <template slot-scope="scope">
                <span style="background:#409EFF;color:#fff;padding:0px 5px;display: inline-block;border-radius: 4px" v-if="scope.row.sendDate != ''">
                    {{scope.row.sendDate}}
                </span>
            </template>
          </el-table-column>
          <el-table-column
            key="12"
            label="实际发货日期"
            width="120"
            align="center">
            <template slot-scope="scope">
                <span style="color:#fff;padding:0px 5px;display: inline-block;border-radius: 4px" v-if="scope.row.shipDate != ''" :style="{'background': scope.row.deliverState < 0 ? '#f56c6c' : '#67c23a'}">
                    {{scope.row.shipDate}}
                </span>
            </template>
          </el-table-column>

          <el-table-column
            label="发货类型"
            width="120"
            align="center" prop="sendType">
          </el-table-column>

          <el-table-column
            label="发货仓库"
            width="120"
            align="center" prop="warehouseName">
          </el-table-column>

          <el-table-column
            label="发货单号"
            width="120"
            align="center" key="102">
            <template slot-scope="scope">
              <el-link @click="toDeliverCon(scope.row)" type="primary" style="font-size:12px;">
                {{scope.row.deliverSn}}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="发货数量"
            width="120"
            align="center">
            <template slot-scope="scope">
              {{scope.row.shipNum}}
            </template>
          </el-table-column>
          <el-table-column
            label="提前发货(天)"
            width="100"
            align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.deliverState < 0 " style="color:Red">{{scope.row.deliverState}}</span>
              <span v-else>{{scope.row.deliverState}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="延迟原因"
            width="150"
            align="center">
            <template slot-scope="scope">
                {{scope.row.delayReason}}
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            fixed="right"
            width="100"
            align="center">
            <template slot-scope="scope">
                <el-button v-if="scope.row.deliverState < 0 " type="text" size="small" @click="showDialog2(scope.row)">延迟发货原因</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery2.pageNum"
          :page-size="listQuery2.pageSize"
          :page-sizes="[10,15,20]"
          :total="count2">
        </el-pagination>
      </div>
    </div>


    <el-dialog  :close-on-click-modal="false" title="修改期望发货时间" :visible.sync="dialogVisible" width="360px">
      <el-form :model="form" size="mini" label-width="120px"  ref="form" :rules="rules">
        <el-form-item label="期望发货时间："  prop="expectSendDate">
          <el-date-picker
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            v-model="form.expectSendDate"
            style="display: inline-block;width:150px"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货紧急度：" prop="urgentType">
          <el-select v-model="form.urgentType" class="input-width" style="width:120px" placeholder="请选择" clearable>
            <el-option :value="item.cddId" :label="item.cddValue" :key="item.cddId" v-for="item in urgentTypeList"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
    </span>
    </el-dialog>

    <el-dialog  :close-on-click-modal="false" title="延迟发货原因" :visible.sync="dialogVisible2" width="360px">
      <el-form :model="form2" size="mini" label-width="100px"  ref="form2" :rules="rules2">
        <el-form-item label="延迟原因："  prop="delayReason">
          <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="form2.delayReason"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2" size="small">取 消</el-button>
        <el-button type="primary" @click="handleConfirm2" :loading="btnLoading4"  size="small">确 定</el-button>
    </span>
    </el-dialog>

  </div>
</template>
<script>

    import {getCustomerSetting,getCustomerOption,myDeptList,saleOrderList,getOrderStatList,getOrderUsersList,getSaleDetailList,exportDetailList,getKingInfo,orderGoodsList,
    changeExpectSendDate,inputDelayReason,getConfigList} from '@/api/partner'
    import {formatDate} from '@/utils/date';
    import {detailListStatistics,addCapitalCost} from '@/api/order'
    import store from '@/store'
    import { mapGetters } from 'vuex'
    import dischargingGoods from '@/views/deliver/dischargingGoods2.vue'
    import {divisionDeptList,tagConfigList} from '@/api/company'
    import crmTag from "@/views/components/crmTag";
    const defaultListQuery={
      pageNum: 1,
      pageSize: 10,
      createDate:null,
      orderState:null,
      orderSn:'',
      userId:null,
      goodsName:'',
      customerName:'',
      type:'sale',
      financeState:[],
      expectSendDate:null,
      sendType:'all',
      sendDate:null,
      isTimeSure:null,
      isMoresuOnlineOrder:null,
      isMoresuNeedCheck:null,
      isChina:'',
      kingGoodsId:'',
      isHasIntroducer:'',
      customerBuyReason:[],
      fromBuyReason:[],
      financeConfirmDate:[],
      financeCancelDate:[],
      checkedCancelDate:[],
      customerNumber:"",
      divsionDeptId:'',
      orderCustomerType:[],
      tagIds:[],
      isDelaySettleOrder:'',
      isNewCustomerOrder:'',
      goodsSn:''
    };
    const defaultListQuery2={
      pageNum: 1,
      pageSize: 10,
      createDate:null,
      orderSn:'',
      goodsName:'',
      kingGoodsId:'',
      deliverState:[],
      sendType:[],
      payTimeState:[],
      "deliverSn" : "", //发货单号
      "isExport" : 0, //是否导出
      tab:'my',
      goodsSn:''
    };
    const defaultForm = {
      expectSendDate:'',
      urgentType:'',
      ogId:'',
    }
    const defaultForm2 = {
      "dgId" : '',
      "delayReason" : ""
    }
    export default {
      name: "index",
      data(){
          return {
              activeIndex: '1',
              creator:'',
              listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
              tableData: [],
              count: 0,
              listLoading: false,
              customerStateList: [],
              userOptionList:[],
              roles:store.getters.roles ? store.getters.roles : [],
              deptList:[],
              orderStateList:[],
              btnLoading2:false,
              JDupdate:'',
              goodsNum:'',
              unSendNum:'',
              actualUnSendNum:'',
              goodsList:[],
              customerBuyReasonList:[],
              fromBuyReasonList:[],

            dialogVisible:false,
            rules:{
              expectSendDate   :[{required: true, message: '此项必填', trigger: 'change'},],
              urgentType   : [{required: true, message: '此项必填', trigger: 'change'},],
            },
            btnLoading:false,
            form:JSON.parse(JSON.stringify(defaultForm)),
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() < Date.now() - 8.64e7
              }
            },
            urgentTypeList:[],

            listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
            tableData2: [],
            count2: 0,
            listLoading2: false,
            btnLoading3:false,
            day1:'',
            day2:'',

            dialogVisible2:false,
            rules2:{
              delayReason   :[{required: true, message: '此项必填', trigger: 'blur'},],
            },
            btnLoading4:false,
            form2:JSON.parse(JSON.stringify(defaultForm2)),
            predictProfit:0,
            allPredictProfit:0,
            orderCustomerTypeList:[],
            divisionList:[],
            tagIdList:[],
            activeNames:['1','2']
          }
      },
      components:{
        dischargingGoods,crmTag,
      },
      computed: {
        ...mapGetters([
          'name',
          'mobile',
          'userId'
        ]),

          isCanSaleByDept(){
              if(this.roles.indexOf("saleDept") != -1){
                  return true
              }else{
                  return false
              }
          },
          isCanSaleByAll(){
              if(this.roles.indexOf("saleAll") != -1){
                  return true
              }else{
                  return false
              }
          },
        saleContractDetailsExport(){
          if(this.roles.indexOf("saleContractDetailsExport") != -1){
            return true
          }else{
            return false
          }
        },
        saleContractDetailStatistics(){
          if(this.roles.indexOf("saleContractDetailStatistics") != -1){
            return true
          }else{
            return false
          }
        },
        departSaleContractDetailStatistics(){
          if(this.roles.indexOf("departSaleContractDetailStatistics") != -1){
            return true
          }else{
            return false
          }
        },
        allSaleContractDetailStatistics(){
          if(this.roles.indexOf("allSaleContractDetailStatistics") != -1){
            return true
          }else{
            return false
          }
        },

        generateCapitalCost(){
          if(this.roles.indexOf("generateCapitalCost") != -1){
            return true
          }else{
            return false
          }
        },
      },
      created() {
        if (localStorage.getItem('saleContractDetails')){
          this.listQuery = JSON.parse(localStorage.getItem('saleContractDetails'));
          localStorage.removeItem('saleContractDetails');
        }
        let time = new Date();
        let day = time - time % (24 * 60 * 60 * 1000) - 8 * 60 * 60 * 1000;
        let end = new Date(day + 24 * 60 * 60 * 1000-1000);
        let start = new Date(day - 7*24 * 60 * 60 * 1000);
        let endDate = formatDate(end, 'yyyy-MM-dd');
        let startDate = formatDate(start, 'yyyy-MM-dd');
        this.listQuery.createDate = [startDate,endDate];
        if(this.$route.query.dataDate){
          this.listQuery.createDate = this.$route.query.dataDate
        }
        if(this.$route.query.dataFinanceState){
          this.listQuery.financeState = this.$route.query.dataFinanceState.split(",")
        }
        if(this.$route.query.dataSendType){
          this.listQuery.sendType = this.$route.query.dataSendType
        }
        if(this.$route.query.dataOrderState){
          this.listQuery.orderState = this.$route.query.dataOrderState
        }
        this.getList();
        this.getUserOptionList();
        this.getDeptList();
        this.getOrderStatListData();
        this.getCustomerSettingList();
        getKingInfo().then((res)=>{
          this.JDupdate = res.orderUpdateTime;
        });
        this.getGoodsList()
        this.getDivisionDeptList()
        this.getOrderCustomerType()
        this.getSelConfigList()
      },
      filters: {
        formatCreateTime(time) {
          if(time){
            let date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
          }else{
            return '--'
          }
        },

        fifFreightType(val){
          if(val == 'sale'){
            return '销售承担运费'
          }else if(val == 'purchase'){
            return '采购承担运费'
          }
        },
        filterIsChina(val){
          if(val== 2){
            return '外贸'
          } else if(val == 1){
            return '内销'
          }
        },
      },
      methods:{
        handleSelectGoodsSn(item){
          if(this.listQuery.sendType =='saleContractDetailStatistics'){
            this.listQuery2.goodsSn = item.goodsSn
          }else{
            this.listQuery.goodsSn = item.goodsSn
          }

        },
        getGoodsList(){
          orderGoodsList().then((res)=>{
            this.goodsList = res.list
          })
        },
        querySearchGoodsSn(queryString, cb){
          let restaurants = this.goodsList;
          let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
          // 调用 callback 返回建议列表的数据
          cb(results);
        },
        createFilter(queryString) {
          return (restaurant) => {
            return (restaurant.goodsSn.indexOf(queryString)!=-1);
          };
        },
        getSelConfigList(){
          tagConfigList().then((res)=>{
            this.tagIdList = res
          })

        },
        //获取订单分类列表
        getOrderCustomerType(){
          getConfigList({status:1}).then((res)=>{
            let orderCustomerType = res.find((el)=>{
              return  el.cdtCode == 'order_customer_type'
            })
            this.orderCustomerTypeList = orderCustomerType ? orderCustomerType.data : []
          })
        },
        //获取事业部列表
        getDivisionDeptList(){
          divisionDeptList().then((res)=>{
            this.divisionList = res
          })
        },
        toSczjcb(item){
          addCapitalCost({ogId:item.ogId}).then((res)=>{
            this.getList()
          })
        },
        handleSelect2(key){
          this.listQuery2.tab = key;
          this.handleSearchList2()
        },
        //查看发货单
        toDeliverCon(item){
          let routeData = this.$router.resolve({name:'deliverCon',query:{id:item.deliverId,type:'see'}});
          window.open(routeData.href);
        },
        handleSizeChange2(val){
          this.listQuery2.pageNum = 1;
          this.listQuery2.pageSize = val;
          this.getList2();
        },
        handleCurrentChange2(val){
          this.listQuery2.pageNum = val;
          this.getList2();
        },

        handleSearchList2(){
          this.listQuery2.pageNum = 1;
          this.getList2();
        },

        //获取合同明细列表
        getList2() {
          if((this.day1 === '' && this.day2  !== '') || (this.day1 !== '' && this.day2  === '')){
            this.$message.error("提前天数必须是范围！")
            return false
          }
          this.listLoading2 = true;
          let listQuery = JSON.parse(JSON.stringify(this.listQuery2));
          listQuery.deliverStateDays = [];
          if(this.day1 !== '' && this.day2  !== ''){
            listQuery.deliverStateDays.push(this.day1,this.day2);
          }

          detailListStatistics(listQuery).then(response => {
            this.tableData2 = response.list;
            this.count2 = response.count;
            this.listLoading2 = false;
          }).catch(()=>{
            this.listLoading2 = false;
          });
        },

        //显示弹窗
        showDialog2(item){
          this.dialogVisible2 = true;
          this.form2 = JSON.parse(JSON.stringify(defaultForm2));
          this.form2.dgId = item.dgId
        },

        //关闭
        handleClose2(){
          this.dialogVisible2 = false;
          this.$refs.form2.clearValidate();
        },

        //提交延迟弹窗
        handleConfirm2(){
          this.$refs['form2'].validate((valid) => {
            if (valid) {
              this.btnLoading4 = true;
              let pa = JSON.parse(JSON.stringify(this.form2));
              inputDelayReason(pa).then((res)=>{
                this.btnLoading4 = false;
                this.dialogVisible2 = false;
                this.getList2();
              }).catch(()=>{
                this.btnLoading4 = false;
              })
            }
          })
        },


        //显示弹窗
        showDialog(item){
          this.dialogVisible = true;
          this.form = JSON.parse(JSON.stringify(defaultForm));
          this.form.expectSendDate = item.expectSendDate;
          this.form.urgentType = item.urgentType;
          this.form.ogId = item.ogId
        },

        //关闭
        handleClose(){
          this.dialogVisible = false;
          this.$refs.form.clearValidate();
        },

        //提交弹窗
        handleConfirm(){
          this.$refs['form'].validate((valid) => {
            if (valid) {
              this.btnLoading = true;
              let pa = JSON.parse(JSON.stringify(this.form));
              changeExpectSendDate(pa).then((res)=>{
                this.btnLoading = false;
                this.dialogVisible = false;
                this.getList();
              }).catch(()=>{
                this.btnLoading = false;
              })
            }
          })
        },
        //获取客户配置
        getCustomerSettingList() {
          getCustomerSetting().then((res) => {
            res.forEach((el) => {
             if(el.cdtCode == 'customer_buy_reason') {
                this.customerBuyReasonList = el.data
              }else if(el.cdtCode == 'from_buy_reason') {
                this.fromBuyReasonList = el.data
              }else if(el.cdtCode == 'urgent_type') {
               this.urgentTypeList = el.data
             }
            });
          })
        },

        //去详情页
        toDetail(type,item){
          let routeData = this.$router.resolve({name:'saleDetail',query:{id:item.orderId,type:type}});
          window.open(routeData.href);
          // this.$router.push({name:'saleDetail',query:{id:item.orderId,type:type}})
        },
        //获取订单状态列表
        getOrderStatListData(){
          getOrderStatList().then((res)=>{
            this.orderStateList = res;
          })
        },
          //获取我的部门列表
          getDeptList(){
            myDeptList().then((res)=>{
              this.deptList = res;
            })
          },
          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList().then((res)=>{
                  this.userOptionList = res;
              })
          },

          //选择员工名称
          handleSelectUserName(key,item){
              this.listQuery[key] = item.userId;
          },


          //客户名称输入匹配
          querySearch(queryString, cb){
              getCustomerOption({keywords:queryString}).then((res)=>{
                  cb(res);
              })
          },


          //选择客户名称
          handleSelectCustomerName(item){
              this.listQuery.keywords = item.customerName
          },

        /**
         * 切换选择状态
         */
        handleSelect(key, keyPath){
          this.listQuery.sendType = key;
          if(key == 'yap'){
            setTimeout(()=>{
              this.$refs.dischargingGoods.init()
            },300)
          }else if(key == 'saleContractDetailStatistics'){
            this.listQuery2 = JSON.parse(JSON.stringify(defaultListQuery2))
            let time = new Date();
            let day = time - time % (24 * 60 * 60 * 1000) - 8 * 60 * 60 * 1000;
            let end = new Date(day + 24 * 60 * 60 * 1000-1000);
            let start = new Date(day - 7*24 * 60 * 60 * 1000);
            let endDate = formatDate(end, 'yyyy-MM-dd');
            let startDate = formatDate(start, 'yyyy-MM-dd');
            this.listQuery2.createDate = [startDate,endDate];
            this.handleSearchList2();
          }else{
              this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
              this.listQuery.sendType = key;
              let time = new Date();
              let day = time - time % (24 * 60 * 60 * 1000) - 8 * 60 * 60 * 1000;
              let end = new Date(day + 24 * 60 * 60 * 1000-1000);
              let start = new Date(day - 7*24 * 60 * 60 * 1000);
              let endDate = formatDate(end, 'yyyy-MM-dd');
              let startDate = formatDate(start, 'yyyy-MM-dd');
              this.listQuery.createDate = [startDate,endDate];
              this.handleSearchList();
          }

        },
        handleSizeChange(val){
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val;
          this.getList();
        },
        handleCurrentChange(val){
          this.listQuery.pageNum = val;
          this.getList();
        },

        handleSearchList(){
          this.listQuery.pageNum = 1;
          this.getList();
        },

        //获取合同明细列表
        getList() {
          this.listLoading = true;
          let listQuery = JSON.parse(JSON.stringify(this.listQuery));
          if(listQuery.isMoresuOnlineOrder != 1){
            listQuery.isMoresuNeedCheck = null;
          }
          getSaleDetailList(listQuery).then(response => {
            this.tableData = response.list;
            this.goodsNum = response.summary.goodsNum;
            this.unSendNum = response.summary.unSendNum;
            this.actualUnSendNum = response.summary.actualUnSendNum;
            this.predictProfit = response.summary.predictProfit;
            this.allPredictProfit = response.summary.allPredictProfit
            this.count = response.count;
            this.listLoading = false;
          }).catch(()=>{
            this.listLoading = false;
          });
        },


        //去客户详情页
        toCustomerDetail(item){
          localStorage.setItem('saleContractDetails', JSON.stringify(this.listQuery));
          this.$router.push({name:'customerDetail',query:{id:item.customerId}})
        },

        //下载excle
        downloadExcel2(){
          if((this.day1 === '' && this.day2  !== '') || (this.day1 !== '' && this.day2  === '')){
            this.$message.error("提前天数必须是范围！")
            return false
          }
          this.btnLoading3 = true;
          let pa =  JSON.parse(JSON.stringify(this.listQuery2));
          pa.deliverStateDays = [];
          if(this.day1 !== '' && this.day2  !== ''){
            pa.deliverStateDays.push(this.day1,this.day2);
          }

          pa.isExport = 1;
          delete pa.pageNum
          delete pa.pageSize
          detailListStatistics(pa).then((res)=>{
            this.btnLoading3 = false;
            require.ensure([], () => {
              const { export_json_to_excel } = require('sheet/Export2Excel');
              const tHeader = res.title;
              const filterVal = res.columns;
              const list = res.list;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, res.fileName);
            })
          }).catch(()=>{
            this.btnLoading3 = false;
          })
        },
        //下载excle
        downloadExcel(){
          this.btnLoading2 = true;
          exportDetailList(this.listQuery).then((res)=>{
            this.btnLoading2 = false;
            require.ensure([], () => {
              const { export_json_to_excel } = require('sheet/Export2Excel');
              const tHeader = res.title;
              const filterVal = res.columns;
              const list = res.list;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, res.fileName);
            })
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        },

        //下载表格数据格式化
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => v[j]))
        },

      },
    }
</script>

<style scoped lang="scss">
  .upload-div{
    text-align: center;
    position:relative;
    #upload{

      opacity: 0;
      position: absolute;
      z-index: 1;
      width:154px;
      height:40px
    }
  }
</style>
<style>
 .pop-goodsSn{
   width:400px;
 }
</style>
